package org.sky.quartz.job;

import com.alibaba.druid.pool.DruidPooledConnection;
import org.apache.logging.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.sky.sys.entity.SysOrgan;
import org.sky.sys.entity.SysUser;
import org.sky.sys.entity.SysUserRole;
import org.sky.sys.service.SysOrganService;
import org.sky.sys.service.SysUserService;
import org.sky.sys.util.BspUtils;
import org.sky.sys.util.multipledatabase.connect.DBConnectionPool;
import org.sky.sys.util.multipledatabase.factory.MultipleConnectFactory;
import org.sky.util.LogUtils;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author weifx
 * @Title: SysUserAndDeptDataTransJob
 * @ProjectName springboot-platform
 * @Description: TODO{用户与部门同步}
 * @date 2019/4/16 12:41
 * @Version 1.0
 */
public class SysUserAndDeptDataTransJob implements Job {
    private final static Logger log = LogUtils.getLogger(SysUserAndDeptDataTransJob.class);
    /**
     * 用户查询SQL
     */
    private final String USER_SELECT_SQL = "SELECT USER_NAME AS CODE,FULL_NAME AS NAME,ORGANIZE_ID AS ORGAN_CODE FROM SYS_FRAME_USER";

    private final String ORGAN_SELECT_SQL = "SELECT ORGANIZE_NO AS CODE,ORGANIZE_NAME AS NAME,ORGANIZE_PARENT_NO AS PAR_CODE FROM SYS_FRAME_ORGANIZE";
    /**
     * 医保审核连接池
     */
    DBConnectionPool auditDatabasePool = MultipleConnectFactory.getDBConnectionPool("auditDatabase");
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        Long begin = System.currentTimeMillis();
        transSysOrgan();
        transSysUser();
        Long end = System.currentTimeMillis();
        log.info("抽取机构与用户数据耗时:{}S",(end-begin)/1000);
    }

    /**
     * 抽取机构信息
     */
    private void transSysOrgan(){
        DruidPooledConnection connection = null;
        PreparedStatement organPS = null;
        ResultSet organRS = null;
        try {
            connection = auditDatabasePool.getConnection();
            organPS = connection.prepareStatement(ORGAN_SELECT_SQL);
            organRS = organPS.executeQuery();
            //源库机构信息
            List<Map> organMapList = new ArrayList<Map>();
            while (organRS.next()) {
                Map map = new HashMap();
                map.put("CODE",organRS.getString("CODE"));
                map.put("NAME",organRS.getString("NAME"));
                map.put("PAR_CODE",organRS.getString("PAR_CODE"));
                organMapList.add(map);
            }
            SysOrganService organSerice = BspUtils.getBean(SysOrganService.class);
            List<SysOrgan> sysOrganList = organSerice.selectAll();
            //发生变化的机构
            List<SysOrgan> updateOrganList = new ArrayList<SysOrgan>();
            //新增的机构
            List<SysOrgan> addOrganList = new ArrayList<SysOrgan>();
            for(Map<String,String> organMap:organMapList){
                //新增机构标记
                boolean addFlag = true;
                for(SysOrgan sysOrgan:sysOrganList){
                    if(organMap.get("CODE").equals(sysOrgan.getCode())){
                        addFlag=false;
                        if(!organMap.get("NAME").equals(sysOrgan.getName())||
                                !organMap.get("PAR_CODE").equals(sysOrgan.getParCode())){
                            sysOrgan.setName(organMap.get("NAME"));
                            sysOrgan.setParCode(organMap.get("PAR_CODE"));
                            updateOrganList.add(sysOrgan);
                        }
                    }
                }
                if(addFlag){
                    SysOrgan sysOrgan = new SysOrgan();
                    sysOrgan.setCode(organMap.get("CODE"));
                    sysOrgan.setName(organMap.get("NAME"));
                    sysOrgan.setParCode(organMap.get("PAR_CODE"));
                    addOrganList.add(sysOrgan);
                }
            }
            organSerice.batchUpdate(updateOrganList);
            organSerice.batchInsert(addOrganList);
        }catch (Exception e){
            log.error("抽取组织机构计划任务出错... ...",e);
        }finally {
            DBConnectionPool.closeConnect(organRS,organPS,connection);
        }
    }

    /**
     * 抽取用户信息
     */
    private void transSysUser(){
        DruidPooledConnection connection = null;
        PreparedStatement userPS = null;
        ResultSet userRS = null;
        try {
            connection = auditDatabasePool.getConnection();
            //源库用户信息
            userPS = connection.prepareStatement(USER_SELECT_SQL);
            userRS = userPS.executeQuery();
            List<Map> userMapList = new ArrayList<Map>();
            while (userRS.next()) {
                Map map = new HashMap();
                map.put("CODE",userRS.getString("CODE"));
                map.put("NAME",userRS.getString("NAME"));
                map.put("ORGAN_CODE",userRS.getString("ORGAN_CODE"));
                userMapList.add(map);
            }
            SysUserService userService = BspUtils.getBean(SysUserService.class);
            List<SysUser> sysUserList = userService.selectAll();
            //变化用户信息
            List<SysUser> updateUserList = new ArrayList<SysUser>();
            //新增用户信息
            List<SysUser> addUserList = new ArrayList<SysUser>();
            //更新用户角色
            List<SysUserRole> addUserRoleList = new ArrayList<SysUserRole>();
            for(Map<String,String> userMap:userMapList){
                //新增用户标记
                boolean addFlag = true;
                for(SysUser sysUser:sysUserList){
                    if(userMap.get("CODE").equals(sysUser.getCode())){
                        addFlag = false;
                        if(!userMap.get("NAME").equals(sysUser.getName())||
                        !userMap.get("ORGAN_CODE").equals(sysUser.getOrganCode())) {
                            sysUser.setName(userMap.get("NAME"));
                            sysUser.setOrganCode(userMap.get("ORGAN_CODE"));
                            updateUserList.add(sysUser);
                        }
                    }
                }
                if(addFlag){
                    SysUser sysUser = new SysUser();
                    sysUser.setCode(userMap.get("CODE"));
                    sysUser.setName(userMap.get("NAME"));
                    sysUser.setOrganCode(userMap.get("ORGAN_CODE"));
                    addUserList.add(sysUser);
                    //用户默认考生角色
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setUserCode(userMap.get("CODE"));
                    sysUserRole.setRoleCode("0003");
                    addUserRoleList.add(sysUserRole);
                }
            }
            userService.batchInsert(addUserList);
            userService.batchUpdate(updateUserList);
            userService.batchInsertUserRole(addUserRoleList);
        }catch (Exception e){
            log.error("抽取用户计划任务出错... ...",e);
        }finally {
            DBConnectionPool.closeConnect(userRS,userPS,connection);
        }
    }
}
